<?php

namespace app\common\model;

use think\Db;
use think\Model;
use traits\model\SoftDelete;

class GoodsSpec extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'goods_spec';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [
		'status_text'
    ];
    
	const STATUS_Y = 1;
	const STATUS_D = 0;
	
	public static $statusList = [
		self::STATUS_Y => '正常',
		self::STATUS_D => '禁用'
	];
 
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ??'';
	}
	public function goods() {
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')
			->setEagerlyType(0);
	}

	public function editSpec($goodsId, $specs) {
		$insData = [];
		//编辑
		$editIds = [];
		if($specs) {
			foreach ($specs as $spec) {
				if($spec['id']) {
					$editIds[] = $spec['id'];
					$editRes = $this->save($spec, ['id' => $spec['id']]);
					if($editRes === false) {
						$this->error = '更改规格出错';
						return false;
					}
				} else if($spec['name'] && $spec['price']) {
					unset($spec['id']);
					$spec['goods_id'] = $goodsId;
					$spec['create_time'] = time();
					$spec['update_time'] = time();
					$insData[] = $spec;
				}
			}
		}
		
		$delRes = Db::name('goodsSpec')
			->where(['goods_id' => $goodsId, 'id' => ['not in', $editIds]])
			->update(['status' => self::STATUS_D, 'delete_time' => time()]);
		
		if($delRes === false) {
			$this->error = '删除规格出错';
			return false;
		}
		
		if($insData) {
			$insRes = $this->insertAll($insData);
			if(!$insRes) {
				$this->error = '添加规格出错';
				return false;
			}
		}
		return true;
	}




}
